package sunwin.yoms.web.controller.person;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.comm.YomsFunction;
import sunwin.yoms.domain.person.UserDomain;
import sunwin.yoms.domain.person.UserRoleDomain;
import sunwin.yoms.service.person.RoleService;
import sunwin.yoms.service.person.UserService;
import sunwin.yoms.web.comm.R;
import sunwin.yoms.web.comm.resolverArg.YomsArrayParam;
import sunwin.yoms.web.comm.YomsAjaxAnswer;
import sunwin.yoms.web.comm.YomsController;

import java.util.List;

/**
 * Created by mt on 2015-8-10.
 */
@Controller
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    /*访问分配角色页面*/
    @RequestMapping(value = R.AllotUserToRole, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.AllotRole, viewName = "person/role.allot")
    public ModelAndView allotUserToRole(@RequestParam(required = false, defaultValue = "0") int roleId) {
        ModelAndView mav = new ModelAndView();
        List<UserDomain> users = userService.getAdmins();
        List<UserRoleDomain> userRoleDomains = roleService.getRoles();

        mav.addObject("users", users);
        mav.addObject("roles", userRoleDomains);
        if (roleId > 0) {
            mav.addObject("roleId", roleId);
        }

        return mav;
    }

    /**
     * 为用户分配/移除角色
     *
     * @param ids   用户的ID集
     * @param value 角色的级别
     * @return
     */
    @RequestMapping(value = R.AllotUserToRole, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.AllotRole)
    @ResponseBody
    public YomsAjaxAnswer allotUserToRole(@YomsArrayParam List<Integer> ids, long value, boolean isRemove) throws YomsException {
        if (isRemove) {
            roleService.cancelAllotUserToRole(ids, value);
        } else {
            roleService.allotUsersToRole(ids, value);
        }
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }
}
